from datetime import datetime
from . import db


class BaseModel(object):
    """模型基类，为每个模型补充创建时间与更新时间"""
    create_time = db.Column(db.DateTime, default=datetime.now)  # 记录的创建时间
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)  # 记录的更新时间


class News(BaseModel, db.Model):
    """新闻"""
    __tablename__ = "info_news"

    id = db.Column(db.Integer, primary_key=True)  # 新闻编号
    title = db.Column(db.String(256), nullable=False)  # 新闻标题
    content = db.Column(db.Text, nullable=False)  # 新闻内容
    index_image_url = db.Column(db.String(256))  # 新闻列表图片路径

class Cases(BaseModel, db.Model):
    """案例"""
    __tablename__ = "info_cases"

    id = db.Column(db.Integer, primary_key=True)  # 案例编号
    title = db.Column(db.String(256), nullable=False)  # 案例标题
    content = db.Column(db.Text, nullable=False)  # 案例内容
    index_image_url = db.Column(db.String(256))  # 案例图片路径
    # 当前案例的所有评论
    comments = db.relationship("Comment", lazy="dynamic")
    category_id = db.Column(db.Integer, db.ForeignKey('info_category.id'))

    def to_case_dict(self):
        resp_dict = {
            "id": self.id,
            "title": self.title,
            "index_image_url": self.index_image_url
        }
        return resp_dict

class Comment(BaseModel, db.Model):
    """评论"""
    __tablename__ = "info_comment"

    id = db.Column(db.Integer, primary_key=True)  # 评论编号
    nick_name = db.Column(db.String(32), unique=True, nullable=False)  # 评论用户昵称
    mobile = db.Column(db.String(11), unique=True, nullable=False)  # 评论用户手机号
    cases_id = db.Column(db.Integer, db.ForeignKey("info_cases.id"), nullable=False)  # 案例id
    content = db.Column(db.Text, nullable=False)  # 评论内容

    def to_dict(self):
        resp_dict = {
            "nick_name": self.nick_name,
            "mobile": self.mobile,
            "content": self.content
        }
        return resp_dict

class Category(BaseModel, db.Model):
    """案例分类"""
    __tablename__ = "info_category"

    id = db.Column(db.Integer, primary_key=True)  # 分类编号
    name = db.Column(db.String(64), nullable=False)  # 分类名
    Cases_list = db.relationship('Cases', backref='category', lazy='dynamic')


